<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/5/11
 * Time: 14:30
 */

namespace bgb\office\word;

class Word
{

    /**
     * 返回文件路径 或下载 或 写入失败
     * @param array $writes [['value' => '', 'type' => 'image', 'style' => []]]
     * @param bool $isDownLoad
     * @return bool|string
     */
    public static function write(array $writes, $isDownLoad = false)
    {
        try {

            if (empty($writes)) throw new \Exception('写入内容为空');

            $phpWord = new \PhpOffice\PhpWord\PhpWord();
            $section = $phpWord->addSection();

            foreach ($writes as $write) {

                if ($write['type'] == 'image') {
                    $section->addImage($write['value'], [
                        'width' => '400',
                        'height' => '200',
                        'align' => 'center'
                    ]);
                } else {
                    $section->addText($write['value'])->setFontStyle([
                        'size' => 12
                    ])->setLineHeight(50);
                }

            }

            $rootDir = ROOT_PATH . '/public';

            $baseDir = '/uploads/words/' . date('Ymd');

            $dir = $rootDir . $baseDir;

            if (!is_dir($dir)) @mkdir($dir, 0755, true);

            $filename = '/' . md5(uniqid(true) . microtime(true)) . '.doc';

            $phpWord->save($dir . $filename, 'Word2007', $isDownLoad);

            return $baseDir . $filename;

        } catch (\Exception $exception) {

            return false;

        }

    }

}